package com.iteaj.iot.boot.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class ConditionalOnIot implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String value;
        if(metadata.getAnnotations().isPresent(ConditionalOnIotServer.class)) {
            MergedAnnotation<ConditionalOnIotServer> annotation = metadata.getAnnotations().get(ConditionalOnIotServer.class);
            value = annotation.getValue("value", String.class).get();
        } else {
            MergedAnnotation<ConditionalOnIotClient> annotation = metadata.getAnnotations().get(ConditionalOnIotClient.class);
            value = annotation.getValue("value", String.class).get();
        }

        try {
            Class.forName(value, false, getClass().getClassLoader());
        } catch (ClassNotFoundException e) {
            return false;
        }

        return true;
    }
}
